﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;

using edowork.com.SQL2005;
using edowork.com.Model;

namespace WebInvoicingsys.system.sale
{
    public partial class sellbill_add : System.Web.UI.Page
    {
        //前台输出提示信息变量
        public string alert_msg = "", Total_qty = "0", Total_price = "0";

        //绑定Session中的货品数据
        private void Bind()
        {
            DataTable dtList = new DataTable();

            dtList.Columns.Add("dgvID");
            dtList.Columns.Add("productcode");
            dtList.Columns.Add("productname");
            dtList.Columns.Add("productshortname");
            dtList.Columns.Add("goodsclassname");
            dtList.Columns.Add("goodsunitname");
            dtList.Columns.Add("goodsspecname");
            dtList.Columns.Add("stackname");
            dtList.Columns.Add("guardname");
            dtList.Columns.Add("qty");
            dtList.Columns.Add("price");
            dtList.Columns.Add("remark");

            DataTable dtData = ((sale_product_class)Session["sale_product"]).getList().Copy();

            foreach (DataRow dr in dtData.Rows)
            {
                DataRow drnew = dtList.NewRow();

                drnew["dgvID"] = (dtList.Rows.Count + 1).ToString();
                drnew["productcode"] = dr["productcode"].ToString();
                drnew["productname"] = dr["productname"].ToString();
                drnew["productshortname"] = dr["productshortname"].ToString();
                drnew["goodsclassname"] = dr["goodsclassname"].ToString();
                drnew["goodsunitname"] = dr["goodsunitname"].ToString();
                drnew["goodsspecname"] = dr["goodsspecname"].ToString();
                drnew["stackname"] = dr["stackname"].ToString();
                drnew["guardname"] = dr["guardname"].ToString();
                drnew["qty"] = dr["qty"].ToString();
                drnew["price"] = dr["price"].ToString();
                drnew["remark"] = dr["remark"].ToString();

                dtList.Rows.Add(drnew);
            }

            rplist.DataSource = dtList;
            rplist.DataBind();
        }

        private void Reset()
        {
            uc_from_saleplan.Reset();
            uc_from_warehouse.Reset();
            uc_from_customer.Reset();
            uc_from_product.clearValue();
            uc_from_settle.Reset();

            txt_phone.Text = "";
            txt_fax.Text = "";
            txt_period.Text = "";
            txt_remark.Text = "";
            txt_marked.Text = "";
            txt_statistical.Text = "";
            txt_ordercoding.Text = "";
            txt_consignee.Text = "";
            txt_address.Text = "";
            txt_testreport.Text = "";
            txt_wayof.Text = "";
            txt_payment.Text = "";
            txt_remark.Text = "";

            txt_qty.Text = "";
            txt_price.Text = "";
            txt_in_remark.Text = "";

            ((sale_product_class)Session["sale_product"]).Reset();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    ((sale_product_class)Session["sale_product"]).Reset();
                }
                catch
                {
                    Session.Add("sale_product", new sale_product_class(Session["connectionString"].ToString()));
                }

                Bind();

                Total_qty = ((sale_product_class)Session["sale_product"]).Total_qty.ToString();
                Total_price = ((sale_product_class)Session["sale_product"]).Total_price.ToString();
            }
        }

        //保存
        protected void btnSave_Click(object sender, EventArgs e)
        {
            alert_msg = "";

            edowork.com.Model.sellbillInfo sellbillInfo = new sellbillInfo();
            edowork.com.Model.sellbilldetailInfo sellbilldetailInfo = new sellbilldetailInfo();

            sellbillInfo.Address = txt_address.Text.Trim();
            sellbillInfo.AmountDue = "";
            sellbillInfo.Arrears = "";
            sellbillInfo.Arrivaldate = uc_arrivaldate.getValue();
            sellbillInfo.B_open = "0";
            sellbillInfo.Billdate = uc_billdate.getValue();
            sellbillInfo.Billtype = "1002";
            sellbillInfo.Checkdate = "";
            sellbillInfo.Checkremark = "";
            sellbillInfo.Checkstu = "0";
            sellbillInfo.Checkuserid = "";
            sellbillInfo.Consignee = txt_consignee.Text.Trim();
            sellbillInfo.Customerid = uc_from_customer.getValue();
            sellbillInfo.Extended = "";
            sellbillInfo.Fax = txt_fax.Text.Trim();
            sellbillInfo.Invoicestu = "0";
            sellbillInfo.M_date = "";
            sellbillInfo.M_ID = "";
            sellbillInfo.M_stu = "0";
            sellbillInfo.Marked = txt_marked.Text.Trim();
            sellbillInfo.Notstiff = "";
            sellbillInfo.Ordercoding = txt_ordercoding.Text.Trim();
            sellbillInfo.Payment = txt_payment.Text.Trim();
            sellbillInfo.Period = txt_period.Text.Trim();
            sellbillInfo.Phone = txt_phone.Text.Trim();
            sellbillInfo.Remark = txt_remark.Text.Trim();
            sellbillInfo.Sepid = uc_from_saleplan.getValue();
            sellbillInfo.Settleid = uc_from_settle.getValue();
            sellbillInfo.Solution = "";
            sellbillInfo.StaffID = "";
            sellbillInfo.Staffremark = "";
            sellbillInfo.Staffstu = "0";
            sellbillInfo.Statistical = txt_statistical.Text.Trim();
            sellbillInfo.Sysdate = DateTime.Now.ToString("yyyy-MM-dd");
            sellbillInfo.Testreport = txt_testreport.Text.Trim();
            sellbillInfo.Userid = Session["userid"].ToString();
            sellbillInfo.Warehouseid = uc_from_warehouse.getValue();
            sellbillInfo.Wayof = txt_wayof.Text.Trim();

            if (String.IsNullOrEmpty(sellbillInfo.Sepid))
            {
                alert_msg = String.Format(Scripts.alert_warning, "请选择销售计划");

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            if (String.IsNullOrEmpty(sellbillInfo.Billdate))
            {
                alert_msg = String.Format(Scripts.alert_warning, "请输入开单日期");

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            if (String.IsNullOrEmpty(sellbillInfo.Warehouseid))
            {
                alert_msg = String.Format(Scripts.alert_warning, "请选择发货仓库");

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            if (String.IsNullOrEmpty(sellbillInfo.Customerid))
            {
                alert_msg = String.Format(Scripts.alert_warning, "请选择销售客户");

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            if (String.IsNullOrEmpty(sellbillInfo.Arrivaldate))
            {
                alert_msg = String.Format(Scripts.alert_warning, "请输入到货日期");

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            if (((sale_product_class)Session["sale_product"]).getListTotal() <= 0)
            {
                alert_msg = String.Format(Scripts.alert_warning, "请输入销售的货品信息");

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            //取得销售单编码
            sellbillInfo.Sabid = SysID.SCR_SaleID(Session["connectionString"].ToString(), ref alert_msg);
            sellbilldetailInfo.Sabid = sellbillInfo.Sabid;


            //保存数据入数据库
            using (edowork.com.SQL2005.TranUtil tranutil = new TranUtil(Session["connectionString"].ToString()))
            {
                System.Data.SqlClient.SqlTransaction tran = null;

                try
                {
                    tran = tranutil.GetSqlTransaction();
                }
                catch (Exception er)
                {
                    alert_msg = String.Format(Scripts.alert_warning, er.Message);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                edowork.com.SQL2005.Execute exec = new Execute(Session["connectionString"].ToString());

                string sql = "";
                int result = -1;
                DataSet dsResult = null;

                //检查当前选择的年份与月份是否在结算日期之前
                sql = String.Format("select * from (select isnull(max(years+months), '') dates from sys_monthly_main) a where a.dates >='{0}{1}'", DateTime.Parse(sellbillInfo.Billdate).ToString("yyyy"), DateTime.Parse(sellbillInfo.Billdate).ToString("MM"));

                dsResult = exec.ExecSQLQueryDataSet(sql, ref alert_msg, tran);

                if ((dsResult == null) || (dsResult.Tables[0].Rows.Count > 0))
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, "当前选择的月份在结算日期之后。");

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }


                //保存入sellbill表
                sql = String.Format(sellbillInfo.SQL_Insert(), sellbillInfo.Sabid, sellbillInfo.Sepid, sellbillInfo.Billtype, sellbillInfo.Billdate,
                                                               sellbillInfo.Warehouseid, sellbillInfo.Customerid, sellbillInfo.Phone, sellbillInfo.Fax,
                                                               sellbillInfo.Settleid, sellbillInfo.Period, sellbillInfo.Arrivaldate, sellbillInfo.Marked,
                                                               sellbillInfo.Statistical, sellbillInfo.Ordercoding, sellbillInfo.Consignee, sellbillInfo.Address,
                                                               sellbillInfo.Testreport, sellbillInfo.Wayof, sellbillInfo.Payment, sellbillInfo.Arrears,
                                                               sellbillInfo.AmountDue, sellbillInfo.Extended, sellbillInfo.Solution, sellbillInfo.Notstiff,
                                                               sellbillInfo.Userid, sellbillInfo.Sysdate, sellbillInfo.Remark, sellbillInfo.StaffID,
                                                               sellbillInfo.Invoicestu, sellbillInfo.Staffstu, sellbillInfo.Staffremark,
                                                               sellbillInfo.Checkuserid, sellbillInfo.Checkdate, sellbillInfo.Checkstu, sellbillInfo.Checkremark,
                                                               sellbillInfo.M_stu, sellbillInfo.M_date, sellbillInfo.M_ID, sellbillInfo.B_open);

                result = exec.ExecSQLQueryInt(sql, ref alert_msg, tran);

                if (result <= 0)
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                DataTable dtData = ((sale_product_class)Session["sale_product"]).getList().Copy();

                foreach (DataRow dr in dtData.Rows)
                {
                    //保存入sellbilldetail表
                    sql = String.Format(sellbilldetailInfo.SQL_Insert(), sellbilldetailInfo.Sabid,
                                        dr["productcode"].ToString(), dr["qty"].ToString(),
                                        dr["price"].ToString(), dr["Remark"].ToString());

                    result = exec.ExecSQLQueryInt(sql, ref alert_msg, tran);

                    if (result <= 0)
                    {
                        tran.Rollback();
                        tranutil.CloseConnection();

                        alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                        return;
                    }
                }

                tran.Commit();
                tranutil.CloseConnection();
            }

            Reset();

            Bind();

            alert_msg = String.Format(Scripts.alert_success, Errormsg.success_Save);

            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
        }

        //重置
        protected void btnReset_Click(object sender, EventArgs e)
        {
            Reset();

            Bind();
        }

        //返回
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            string url = "/system/sale/sellbill.aspx";

            Response.Redirect(url);
        }

        //添加产品
        protected void btAddproduct_Click(object sender, EventArgs e)
        {
            alert_msg = "";

            string productu_code = uc_from_product.getValue();
            string qty = txt_qty.Text.Trim();
            string in_price = txt_price.Text.Trim();
            string in_remark = txt_in_remark.Text.Trim();

            if (((sale_product_class)Session["sale_product"]).Add(productu_code, qty, in_price, in_remark, ref alert_msg) == false)
            {
                alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            uc_from_product.clearValue();
            txt_qty.Text = "";
            txt_price.Text = "";
            txt_in_remark.Text = "";

            Bind();

            Total_qty = ((sale_product_class)Session["sale_product"]).Total_qty.ToString();
            Total_price = ((sale_product_class)Session["sale_product"]).Total_price.ToString();
        }

        //删除货品
        protected void rplist_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            string id = e.CommandArgument.ToString();

            switch (e.CommandName)
            {
                case "Delete":
                    {
                        ((sale_product_class)Session["sale_product"]).Delect(id);

                        //查询
                        Bind();

                        Total_qty = ((sale_product_class)Session["sale_product"]).Total_qty.ToString();
                        Total_price = ((sale_product_class)Session["sale_product"]).Total_price.ToString();

                        alert_msg = String.Format(Scripts.alert_success, Errormsg.success_Delete);

                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);


                        break;
                    }
                default:
                    {
                        break;
                    }
            }
        }

        //销售客户选择
        protected void uc_from_customer_OnbtSelect_Click(object sender, EventArgs e)
        {
            edowork.com.SQL2005.Execute exec = new Execute(Session["connectionString"].ToString());

            string customerid = uc_from_customer.getValue();

            string sql = String.Format("select customerid, customername, address, contact, mobile, email, phone, fax, qq, settleid from customer where customerid='{0}'", customerid);

            DataSet ds = exec.ExecSQLQueryDataSet(sql);

            if (ds == null)
            {
                return;
            }

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                txt_phone.Text = dr["phone"].ToString();
                txt_fax.Text = dr["fax"].ToString();

                uc_from_settle.SetByValue(dr["settleid"].ToString());
            }
        }
    }
}